<template>
  <div class="resident-detail-page">
    <nav-bar :title="title"></nav-bar>
    <div class="resident-detail-main page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <div class="van-collapse">
            <van-field
              required
              readonly
              clickable
              v-model="formParams.placeName"
              label="所属场所"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.placeName"
              @input="getBuild"
              @click="houseOpenPopup('place')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="formParams.buildName"
              label="楼栋"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.buildName"
              @input="getUnit"
              @click="houseOpenPopup('build')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="formParams.unitName"
              label="单元"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.unitName"
              @input="getFloor"
              @click="houseOpenPopup('unit')"
            />
            <van-field
              required
              readonly
              clickable
              v-model="formParams.floorName"
              label="楼层"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.floorName"
              @click="houseOpenPopup('floor')"
            />
            <van-field
              required
              name="houseName"
              v-model="formParams.houseName"
              label="房屋名称"
              placeholder="请输入"
              right-icon="arrow"
              class="van-field__right-icon-white"
              :maxlength="20"
              :rules="rules.houseName"
            />
            <van-field
              required
              type="digit"
              name="roomNo"
              v-model="formParams.roomNo"
              label="房间号"
              placeholder="请输入"
              right-icon="arrow"
              class="van-field__right-icon-white"
              :maxlength="6"
              :rules="rules.roomNo"
            />
            <van-field
              required
              readonly
              clickable
              name="houseTypeName"
              v-model="formParams.houseTypeName"
              label="房屋类别"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.houseTypeName"
              @click="dictOpenPopup('houseType')"
            />
            <van-field
              required
              readonly
              clickable
              name="houseStateName"
              v-model="formParams.houseStateName"
              label="房屋使用形式"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.houseStateName"
              @click="dictOpenPopup('houseState')"
            />
            <van-field
              required
              readonly
              clickable
              name="housePropertyName"
              v-model="formParams.housePropertyName"
              label="房屋性质"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.housePropertyName"
              @click="dictOpenPopup('houseProperty')"
            />
            <van-field
              type="digit"
              name="houseNum"
              v-model="formParams.houseNum"
              label="房间数"
              placeholder="请输入"
              right-icon="arrow"
              class="van-field__right-icon-white"
              :maxlength="2"
            />
            <van-field
              type="digit"
              name="houseArea"
              v-model="formParams.houseArea"
              label="房屋面积"
              right-icon="arrow"
              placeholder="请输入"
              class="van-field__right-icon-white"
              :maxlength="7"
            />
            <van-field label="备注" readonly :border="false" />
            <van-field
              name="remark"
              v-model="formParams.remark"
              placeholder="请输入备注……"
              rows="5"
              autosize
              type="textarea"
              show-word-limit
              :border="false"
              input-align="left"
              class="van-field__value--textarea"
              :maxlength="200"
            />
          </div>
          <div style="padding: 16px">
            <van-button block type="info" native-type="submit" :disabled="buttonDisabled">更新</van-button>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
      />
    </van-popup>
    <!-- 所属场所 -->
    <van-popup v-model="housePopupShow" round position="bottom">
      <van-picker
        show-toolbar
        :default-index="
          houseData[`${houseType}Data`] &&
          houseData[`${houseType}Data`].findIndex(o => o.code === formParams[`${houseType}Code`])
        "
        :columns="houseData[`${houseType}Data`]"
        value-key="title"
        @cancel="housePopupShow = false"
        @confirm="houseOnConfirm"
      />
    </van-popup>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import SelectPopup from '@/mixins/selectPopup'
import General from '@/api/general'
import Resident from '@/api/resident'
import { FormParams } from './libs/house'
export default {
  mixins: [SelectPopup],
  data() {
    return {
      title: '房屋基础信息更新',
      dictTypes: 'houseType,houseState,houseProperty',

      buttonDisabled: false,
      formParams: new FormParams(),
      rules: {
        placeName: [{ required: true, message: '请选择所属场所' }],
        buildName: [{ required: true, message: '请选择楼栋' }],
        unitName: [{ required: true, message: '请选择单元' }],
        floorName: [{ required: true, message: '请选择楼层' }],
        houseName: [
          { required: true, message: '请输入房屋名称' },
          { validator: this.checkHouseName, message: '该房屋名称已使用' }
        ],
        roomNo: [
          { required: true, message: '请输入房间号' },
          { validator: this.checkRoomNo, message: '该房间号已使用' }
        ],
        houseTypeName: [{ required: true, message: '请选择房屋类别' }],
        houseStateName: [{ required: true, message: '请选择房屋使用形式' }],
        housePropertyName: [{ required: true, message: '请选择房屋性质' }]
      },
      // 房屋信息
      houseType: '',
      housePopupShow: false,
      houseData: {
        placeData: [],
        buildData: [],
        unitData: [],
        floorData: []
      },
      houseFlag: this.$route.query.houseCode
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  watch: {
    'formParams.placeCode'() {
      this.getBuild()
    },
    'formParams.buildCode'() {
      this.getUnit()
    },
    'formParams.unitCode'() {
      this.getFloor()
    }
  },
  created() {
    // 字典项
    this.getDict(this.dictTypes)
    // 场所
    this.getPlace()
    // 更新
    if (this.$route.query.houseCode) {
      this.getDetail()
    }
  },
  methods: {
    // 获取详情
    getDetail() {
      Resident.BaseInfo.houseDetail({
        houseCode: this.$route.query.houseCode,
        queryType: this.$route.query.queryType
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.formParams = { ...data }
        }
      })
    },
    // 房屋所属场所
    getPlace() {
      const params = {
        regionCode: this.user.regionCode
      }
      General.Region.getPlace(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.placeData = data
        }
      })
    },
    getBuild() {
      if (!this.houseFlag) {
        this.houseData = {
          placeData: this.houseData.placeData,
          buildData: [],
          unitData: [],
          floorData: []
        }
        this.formParams.buildCode = ''
        this.formParams.buildName = ''
        this.formParams.unitCode = ''
        this.formParams.unitName = ''
        this.formParams.floorCode = ''
        this.formParams.floorName = ''
      }
      const params = {
        placeCode: this.formParams.placeCode
      }
      General.Region.getBuild(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.buildData = data
        }
      })
    },
    getUnit() {
      if (!this.houseFlag) {
        this.houseData = {
          placeData: this.houseData.placeData,
          buildData: this.houseData.buildData,
          unitData: [],
          floorData: []
        }
        this.formParams.unitCode = ''
        this.formParams.unitName = ''
        this.formParams.floorCode = ''
        this.formParams.floorName = ''
      }
      const params = {
        buildCode: this.formParams.buildCode
      }
      General.Region.getUnit(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.unitData = data
        }
      })
    },
    getFloor() {
      if (!this.houseFlag) {
        this.houseData.floorData = []
        this.houseData.houseData = []
        this.formParams.floorCode = ''
        this.formParams.floorName = ''
      }
      const params = {
        buildCode: this.formParams.buildCode,
        unit: this.formParams.unitCode
      }
      General.Region.getFloor(params).then(res => {
        const { data, status } = res.data
        if (status === 0) {
          this.houseData.floorData = data
          this.houseFlag = ''
        }
      })
    },
    houseOpenPopup(houseType) {
      if (!this.houseData[`${houseType}Data`].length) {
        this.$toast('暂无数据')
        return false
      }
      this.houseType = houseType
      this.housePopupShow = true
    },
    houseOnConfirm(item) {
      this.formParams[`${this.houseType}Code`] = item.code
      this.formParams[`${this.houseType}Name`] = item.title
      this.housePopupShow = false
    },
    // 房屋名称判重
    checkHouseName() {
      return new Promise((resolve, reject) => {
        Resident.Init.houseCheck({
          houseCode: this.formParams.houseCode,
          buildCode: this.formParams.buildCode,
          unitCode: this.formParams.unitCode,
          floorCode: this.formParams.floorCode,
          houseName: this.formParams.houseName
        }).then(res => {
          resolve(res.data.status === 0)
        })
      })
    },
    // 房屋号判重
    checkRoomNo() {
      return new Promise((resolve, reject) => {
        Resident.Init.houseCheck({
          houseCode: this.formParams.houseCode,
          buildCode: this.formParams.buildCode,
          unitCode: this.formParams.unitCode,
          floorCode: this.formParams.floorCode,
          roomNo: this.formParams.roomNo
        }).then(res => {
          resolve(res.data.status === 0)
        })
      })
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.buttonDisabled = true
      Resident.BaseInfo.houseUpdate(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$router.push({
              path: '/page/message',
              query: {
                backTo: this.$route.query.type ? '-2' : '-1',
                title: this.$route.query.type ? '更新成功' : '提交成功'
              }
            })
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@/assets/style/resident/detail.less';
</style>
